<!doctype html> 
<html> 
<head> 
    <meta charset="utf-8"> 
    <title></title> 

<style type="text/css">
	
	#div{
		width: 100px;height: 100px;
		background: black;
		position: absolute;
		left: 100px;top: 100px;
	}
	#div2{
		width: 10px;height: 10px;
		background: red;position: absolute;
		left: 10px;top: 10px;
	}
</style>

</head>
<body>

	<div id='div'>
		
	</div>
	<script type="text/javascript">

div.onmousedown = function(e){
	var ev = e || event;
	var posX = ev.clientX - this.offsetLeft;
	var posY = ev.clientY - this.offsetTop;

	document.onmousemove = function(e){
		var ev = e || event;
		var l = ev.clientX - posX;
		var t = ev.clientY - posY;
		var maxW = innerWidth - div.offsetWidth;
		var maxH = innerHeight - div.offsetHeight;

		l = l < 0 ? 0 : l;
		l = l > maxW ? maxW : l;
		t = t < 0 ? 0 : t;
		t = t > maxH ? maxH : t;
	
		div.style.left = l + 'px';
		div.style.top = t + 'px';
	}
	document.onmouseup = function(){
		document.onmousemove =null;
		document.onmouseup = null;
	}



}

	</script>
</body>
</html>